<?php defined('SYSPATH') or die('No direct script access.');

class Model_Product extends ORM
{  
    protected $_reload_on_wakeup = false;
    
    const PRODUCTS_PER_PAGE = 30;
    
    /**
    * TODO ограничение на товары текущего магазина
    * 
    */
    /*public function __construct()
    {
        
    }*/
    
    /**
    * Добавление нового товара
    * 
    * @param int $shop_id       - id магазина
    * @param mixed $source_id   - id в магазине
    * @param string $url        - адрес товара в магазине        
    * @param string $name       - название
    * @return ORM
    */
    public function add_product(Model_Shop $shop, $source_id, $category_id, $url, $name, $picture = null)
    {
        $this->shop_id   = $shop->id;
        $this->source_id = $source_id;
        $this->category_id = $category_id;
        $this->url       = $url;
        $this->name      = $name;
        $this->clean_name = $this->_get_clean_name($name);
        if ($picture) {
            $this->picture = $picture;    
        }
        $this->save();
        
        /*if ($model = ORM::factory('model')->calculate_model($this)) {
            $this->model_id = $model->id;
            $this->save();
        }*/
        
        return $this;  
    } 
    
    protected function _get_clean_name($name)
    {
        // TODO Если есть слово "для", то оставляем все как есть (???)
        
        $name = $this->_cut_trash($name);
        $words = $this->_get_words($name);
        
        $morphy = Morphy::instance();
        $result = array();
        foreach ($words as $word) {
            $word = mb_strtoupper(trim($word));
            if (!$word) {
                continue;
            }
            
            // Если не нашли, значит либо название товара, либо еще что-то
            // Сохраняем, а русские слова удаляем
            if (!($part_of_speech = $morphy->getPartOfSpeech($word))) {
                $result[] = $word;         
            }   
        }
        
        return implode(' ', $result);
    }
    
    protected function _cut_trash($name)
    {
        // Вырезаем содержимое скобок - (серый)
        // Чаще всего там мусор или цвет
        $name = $this->_cut_brackets($name); 
        
        // TODO Вырезать " и &quot (???)
        //$name = $this->_cut_quotes($name); 
        
        // TODO Удалять все, что справа "+"      
        
        return trim($name);
    }
    
    protected function _cut_brackets($name, $cut_single_bracket = true)
    {
        $result = preg_replace('/(\([^\)]+\))/i', '', $name);
        if ($cut_single_bracket) {
            $result = preg_replace('/(\([^\)]+)/i', '', $result);    
        }
        return $result;   
    }
    
    protected function _cut_quotes($name)
    {
        return $name;
    }
    
    protected function _get_words($name)
    {
        $words = explode(' ', $name);
        
        // Удаляем запятые
        foreach ($words as &$word) {
            $word = str_replace(',', '', $word);    
        }
        
        return $words;
    }
    
    public function get_products($category = null, $model = null, $page = null, $get_count = false, $order_by = 'id')
    {
        $query = $this->_get_products_query();
        if ($category !== null) {
            $category_id = $category;
            if (is_object($category)) {
                $category_id = $category->source_id;
            }
            $query->where('category_id', '=', $category_id);
        }
        
        if ($model === true) {
            $query->where('model_id', '!=', 0);    
        } else if ($model !== null) {
            $model_id = $model;
            if (is_object($model)) {
                $model_id = $model->id;
            }
            $query->where('model_id', '=', $model_id);
        }
        
        if ($page) {
            $count = $this->get_products_per_page();
            $offset = ($page - 1) * $count;
            $query->offset($offset)->limit($count);    
        }
        
        if ($order_by) {
            $query->order_by($order_by, 'ASC');   
        }
        
        if ($get_count) {
            return $query->count_all();   
        }
        return $query->find_all();  
    }
    
    /**
    * put your comment there...
    * 
    * @param mixed $product
    */
    public function get_next_unsorted_product($product)
    {
        $query = $this->_get_products_query()
                    ->where('model_id', '=', 0)
                    ->where('id', '>', $product->id)
                    ->where('category_id', '=', $product->category_id)
                    ->order_by('id', 'ASC')
                    ->limit(1);
        $product = $query->find();
        if ($product->loaded()) {
            return $product;
        }
        return null;
    }
    
    /**
    * put your comment there...
    * 
    * @param mixed $source_id
    */
    public function get_product($source_id)
    {
        $query = $this->_get_products_query()
                    ->where('source_id', '=', $source_id)
                    ->limit(1);
        $product = $query->find();
        if ($product->loaded()) {
            return $product;
        }
        return null;
    }
    
    public function get_shop_products(Model_Shop $shop = null)
    {
        if (!$shop) {
            $shop = ORM::factory('shop')->get_current();    
        }
        return ORM::factory('product')
                ->where('shop_id', '=', $shop->id)
                ->find_all();
    }
    
    public function get_products_per_page()
    {
        return self::PRODUCTS_PER_PAGE;
    }
    
    protected function _get_products_query()
    {
        return ORM::factory('product')->where('shop_id', '=', ORM::factory('shop')->get_current()->id);   
    }
    
    /**
    * put your comment there...
    * 
    * @param Model_Model $model
    */
    public function to_model(Model_Model $model)
    {
        $this->model_id = $model->id;
        $this->save();
        
        ORM::factory('model')->delete_potential_models($this);    
    }
    
    public function get_clean_name()
    {
        return Model_Main::get_clean_name($this->clean_name);
    }
}